<template>
  <a-scrollbar style="height: calc(100vh - 40px); overflow: auto; padding-bottom: 10px">
    <div class="publish-detail-con">
      <div class="left">
        <div class="tab-top">
          <a-tabs v-model:active-key="curTab">
            <a-tab-pane key="1" title="商品描述" />
            <a-tab-pane key="2" title="商品数据" />
          </a-tabs>
        </div>
        <!-- 商品描述 -->
        <div v-if="curTab === '1'" class="goods-desc mt10">
          <!-- 标题区域 -->
          <div class="title">
            <!-- <div class="more-language">
              <div @click="curLanguageTab == index" :class="[curLanguageTab == index ? 'active' : '']" v-for="(item, index) of languageList" :key="index">{{ item.name }}</div>
            </div> -->
            <div class="title-input">
              <div class="required">
                <span>标题</span>
                <span v-if="productInfo.mallSourceUrl" style="margin-left: 20px" class="common-text">
                  <span>原URL：</span>
                  <span>{{ productInfo.mallSourceUrl }}</span>
                  <span>
                    <icon-link style="font-size: 18px" @click="jump" class="highlight cursor" />
                  </span>
                </span>
              </div>
              <div>
                <a-input v-model="form.title" placeholder="请输入标题" />
              </div>
              <!-- <div class="mt5">
                <div class="flex-c">
                  <div class="required">固定链接：</div>
                  <div class="flex-c">
                    <span class="common-text" style="font-size: 14px">{{ domain }}</span>
                    <a-input style="width: 400px" v-model="form.link" placeholder="请输入固定链接" />
                  </div>
                </div>
              </div> -->
            </div>
          </div>
          <!-- 商品简短描述 -->
          <div class="short-desc mt10">
            <div class="required">商品要点</div>
            <editor v-model="form.shortDesc" :height="200" :excludeKeys="['group-image', 'group-video', 'insertTable', 'codeBlock', 'emotion']" />
          </div>
          <!-- 商品描述 -->
          <div class="desc mt10">
            <div class="required">描述</div>
            <editor v-model="form.desc" :height="200" />
            <!-- <editor :value="form.desc" :height="200" /> -->
          </div>

          <!-- 商品标签 -->
          <div class="goods-tag mt10">
            <div>商品标签</div>

            <!-- <div class="tag-con mt5">
              <a-tag @click="selTag(item)" class="cursor mr5" v-if="tagList[0]" v-for="(item, index) of tagList" :key="index" color="arcoblue" bordered>{{ $extract(item, 'dataFromRestApi.name') }}</a-tag>
              <a-empty v-else description="暂无标签" />
            </div>
            <div class="mt10">已添加的标签</div> -->
            <div class="flex-c">
              <!-- <a-input style="width: 800px" v-model="tagName" placeholder="批量添加请使用英文半角逗号隔开" /> -->
              <a-select :style="{ width: '800px' }" @change="handleSelectTag" v-model="tagName" allow-search :loading="loading" placeholder="请输入选择" @search="handleSearchTag" :filter-option="false">
                <a-option v-for="item of tagList" :value="item.id">{{ item.dataFromRestApi.name }}</a-option>
              </a-select>
              <a-button class="gray-outline ml5" @click="quickAddTag">添加</a-button>
            </div>
            <div class="tag-con mt5">
              <a-tag v-if="selTagList[0]" class="mr5" v-for="(item, index) of selTagList" :key="index" color="arcoblue" bordered>
                <a-space>
                  <div>{{ item.name }}</div>
                  <div class="cursor" @click="deleteSelTag(index)">
                    <icon-close />
                  </div>
                </a-space>
              </a-tag>
              <a-empty v-else description="暂无标签" />
            </div>
          </div>
        </div>
        <!-- 商品数据 -->
        <div v-else class="goods-data">
          <!-- 商品类型 -->
          <div class="goods-type">
            <a-space>
              <div>类型</div>
              <div class="ml10">
                <a-radio-group disabled v-model="form.goodsType">
                  <a-radio value="variable">变体</a-radio>
                </a-radio-group>
              </div>
              <div>
                <span class="common-text">主体商品SKU：</span>
                <span>{{ subjectSku }}</span>
              </div>
            </a-space>
          </div>
          <!-- 商品属性 -->
          <div class="goods-property mb10">
            <div class="required mb5">商品属性</div>
            <shopProperty type="edit" :list="attrList" :shopId="productInfo.shopId" @save="saveProperty" />
            <!-- <a-button class="gray-outline" @click="showModal('add')">添加属性</a-button>

            <a-table size="mini" :data="attrList" :pagination="false" class="table-single-line mt5" :scroll="{ x: '100%', y: 300 }">
              <template #columns>
                <a-table-column title="属性ID" #cell="{ record }">
                  {{ record.id }}
                </a-table-column>
                <a-table-column title="属性名称" #cell="{ record }">
                  {{ record.name }}
                </a-table-column>
                <a-table-column title="可见性" #cell="{ record }">
                  <div v-if="record.visible">产品页可见</div>
                  <div v-if="record.variation">变体可用</div>
                </a-table-column>
                <a-table-column title="属性值" #cell="{ record }" :width="300">
                  <TextLimit position="top" :val="record.options.join('，')"></TextLimit>
                </a-table-column>
                <a-table-column title="操作" #cell="{ record, rowIndex }" :width="80">
                  <a-space>
                    <a-button type="text" @click="showModal('edit', record)">编辑</a-button>
                    <a-button type="text" style="color: red" @click="attrList.splice(rowIndex, 1)">删除</a-button>
                  </a-space>
                </a-table-column>
              </template>
            </a-table> -->
          </div>
          <!-- 商品变体 -->
          <div class="goods-variant">
            <div class="required mb5">商品变体</div>
            <productVariant ref="ProductVariant" :picList="goodsImgForm.windowPicList" :attList="attrList" :info="productInfo" :shopId="productInfo.shopId" />
          </div>
        </div>
        <!-- 保存按钮 -->
        <div class="flex-c-c" style="background-color: white; padding: 10px 0">
          <a-button type="primary" :loading="saveBasicInfoOrgoodsDataLoading" @click="saveBasicInfoOrgoodsData">保存</a-button>
          <!-- <a-button type="primary" class="ml10">保存并提交审核</a-button> -->
        </div>
      </div>
      <div class="right">
        <div class="goods-status edit-info-box">
          <div class="top">
            <div>商品发布状态</div>
            <div>
              <a-button size="mini" type="primary" @click="savePublishStatus">保存</a-button>
            </div>
          </div>
          <div class="bottom">
            <div>
              <a-space>
                <div style="width: 90px; text-align: right">运营：</div>
                <a-select style="width: 200px" allow-search v-model="goodsPublishForm.operationUserId" placeholder="请选择运营">
                  <a-option v-for="(item, index) of userList" :key="index" :label="item.userName" :value="item.id"></a-option>
                </a-select>
              </a-space>
            </div>
            <!-- <div>
              <a-space>
                <div style="width: 90px; text-align: right">可见性：</div>
                <a-select style="width: 200px" v-model="goodsPublishForm.visiable" placeholder="请选择">
                  <a-option value="publish">公开</a-option>
                  <a-option value="private">私密</a-option>
                </a-select>
              </a-space>
            </div> -->
            <div class="mt10">
              <a-space>
                <div style="width: 90px; text-align: right">可见范围：</div>
                <a-select style="width: 200px" v-model="goodsPublishForm.range" placeholder="请选择">
                  <a-option value="visible">商店页和搜索结果页</a-option>
                  <a-option value="catalog">仅商店页</a-option>
                  <a-option value="search">仅搜索结果页</a-option>
                  <a-option value="hidden">隐藏</a-option>
                </a-select>
              </a-space>
            </div>
            <div class="mt10">
              <a-space>
                <div style="width: 90px; text-align: right">是否推荐：</div>
                <a-radio-group v-model="goodsPublishForm.featured">
                  <a-radio :value="true">是</a-radio>
                  <a-radio :value="false">否</a-radio>
                </a-radio-group>
              </a-space>
            </div>
          </div>
        </div>
        <div class="goods-img edit-info-box mt10">
          <div class="top">
            <div>商品图片</div>
            <div>
              <a-button size="mini" type="primary" @click="saveProductImg">保存</a-button>
            </div>
          </div>
          <div class="bottom" style="padding: 10px">
            <!-- <div class="common-text">点击图片修改图片</div> -->
            <div class="master-img-con">
              <a-upload disabled :show-file-list="false" list-type="picture-card" action="/" :on-before-upload="(file) => beforeUplaod(file, 'master')">
                <template #upload-button v-if="goodsImgForm.windowPicList[0]">
                  <img :src="getImgForHttp($extract(goodsImgForm.windowPicList[0], 'src'))" alt="" style="width: 200px; height: 200px" />
                </template>
              </a-upload>
            </div>
            <div>
              <span>上传橱窗图</span>
              <span class="common-text ml5">拖动可排序</span>
            </div>
            <div class="product-img-box">
              <div class="box">
                <div class="product-sort-con">
                  <div class="box-img-con" v-for="(item, index) of goodsImgForm.windowPicList" :key="index">
                    <div class="mask">
                      <div class="btn-con">
                        <!-- <icon-eye class="cursor" style="margin-right: 15px" /> -->
                        <icon-delete class="cursor" @click.stop="goodsImgForm.windowPicList.splice(index, 1)" />
                      </div>
                    </div>
                    <div class="my-image" @click="showImgPre(index)">
                      <a-image :preview="false" :src="getImgForHttp(item.src)" width="80px" height="80px" />
                    </div>
                  </div>
                </div>
                <div class="fl" style="width: 80px; height: 80px">
                  <a-upload class="fl" :show-file-list="false" list-type="picture-card" action="/" :on-before-upload="(file) => beforeUplaod(file, 'windowPic')" />
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="goods-category edit-info-box mt10">
          <div class="top">
            <div>商品类别</div>
            <div>
              <a-button size="mini" type="primary" @click="saveProductCategory">保存</a-button>
            </div>
          </div>
          <div class="bottom" style="padding: 10px">
            <a-tree :checkable="true" check-strictly block-node v-model:expanded-keys="expandedCateGoryIds" v-model:checked-keys="selCateGoryIds" :data="categoryList">
              <template #extra="nodeData">
                <!-- <a-button type="text">设为主要</a-button> -->
              </template>
            </a-tree>
          </div>
        </div>

        <!-- <div class="goods-brand edit-info-box mt10">
          <div class="top">
            <div>商品品牌</div>
            <div>
              <a-button size="mini" type="primary">保存</a-button>
            </div>
          </div>
          <div class="bottom" style="padding: 10px">
            <a-scrollbar style="max-height: 200px; overflow: auto">
              <a-radio-group direction="vertical">
                <a-radio :value="item.id" v-for="(item, index) of brandList" :key="index">{{ item.name }}</a-radio>
              </a-radio-group>
            </a-scrollbar>
          </div>
        </div> -->
      </div>
    </div>
  </a-scrollbar>

  <!-- 编辑属性 -->
  <editAttr v-if="showEditAttrModal" v-model="showEditAttrModal" :shopId="productInfo.shopId" :info="editAttrInfo" :type="editAttrType" :selAttList="attrList" @save="saveAttr" />

  <a-image-preview-group v-model:visible="visible" v-model:current="current" infinite :srcList="goodsImgForm.windowPicList.map((e:any) => e.src)" />
</template>

<script lang="ts" setup>
  import { defineComponent, ref, nextTick, onMounted } from 'vue'
  import { OSSUpload } from '@/utils/ossUpload'
  import { findChildrenArray, getImgForHttp } from '@/utils'
  import { getProductSPUList, saleGetById, listAllCategoryTreeByShopId, tagRollPage, getBrandList, batchTag, batchProduct, batchProductVariation, saleBatchUpdate } from '@/api/product'
  import { getOrganizesUser } from '@/api/system'
  import { Message } from '@arco-design/web-vue'
  import { useRouter, useRoute } from 'vue-router'
  import editor from '@/components/wangeditor/editor.vue'
  import productVariant from './components/productVariant.vue'
  import editAttr from './components/editAttr.vue'
  import shopProperty from '../publish/components/shopProperty.vue'
  import Sortable from 'sortablejs'
  import dayjs from 'dayjs'

  const ProductVariant = ref()
  const router = useRoute()
  let curTab = ref('1')
  let editAttrType = ref('add')
  let editAttrInfo = ref({})
  let showEditAttrModal = ref(false)
  let loading = ref(false)
  let saveBasicInfoOrgoodsDataLoading = ref(false)
  let subjectSku = ref('') // 主体SKU
  let curLanguageTab = ref(0) // 以后多语言切换的时候用户，暂时无用
  let languageList = ref([{ name: '英语' }])
  let attrList: any = ref([]) // 已选择的属性信息
  let domain = ref('') // 域名
  let productInfo: any = ref({}) // 编辑的商品信息
  let brandList: any = ref([]) //品牌信息
  let categoryList: any = ref([]) //分类信息
  let tagList: any = ref([]) //标签信息
  let selTagList: any = ref([]) // 已经选中的标签
  let selCateGoryIds: any = ref([]) // 选中的分类Id
  let expandedCateGoryIds: any = ref([]) // 默认展开的树Id
  let userList: any = ref([]) //
  let form: any = ref({
    title: '', // 标题
    link: '', // 固定链接
    desc: '', //商品描述
    shortDesc: '', //商品简短描述
    goodsType: 'variable', // 商品类型
  })

  let goodsPublishForm = ref({
    visiable: 'publish', //可见性
    range: 'visible', //可见范围
    featured: false, //可见性
    operationUserId: '',
  })

  let goodsImgForm: any = ref({
    windowPicList: [],
    img: '',
  })

  let tagName = ref('') // 添加标签

  let current = ref(1)
  let visible = ref(false)
  let searchSpuLoading = ref(false)

  let spuList: any = ref([])
  let spuInfo: any = ref({}) // spu信息
  let selPropertyList: any = ref([])

  // 上传
  const beforeUplaod = async (file: File, type: string) => {
    const res: any = await OSSUpload(file)
    let obj = {
      src: res.url,
    }
    goodsImgForm.value.windowPicList.push(obj)
  }

  // 图片预览
  const showImgPre = (index: number) => {
    current.value = index
    visible.value = true
  }
  const imgUrl = (info: any) => {
    return info.productPicList[0]?.url || ''
  }

  const handleChangeSku = (val: string) => {
    let item = spuList.value.find((item: any) => item.id == val)
    if (item) {
      spuInfo.value = item
    } else {
      spuInfo.value = {}
    }
  }

  const handleSearch = async (value: string) => {
    if (value) {
      try {
        searchSpuLoading.value = true
        const res: any = await getProductSPUList({ keyword: value, searchType: 'exact', keywordType: 'spu' })
        spuList.value = res.data?.records || []
      } catch (error) {}
      searchSpuLoading.value = false
    } else {
      spuList.value = []
    }
  }

  // 初始化拖拽
  const rowDropProductImg = () => {
    const body: any = document.querySelector('.product-sort-con')
    if (!body) return
    Sortable.create(body, {
      animation: 200, // 定义排序动画的时间
      forceFallback: true,
      sort: true,
      handle: '.my-image',
      onEnd(evt: any) {
        goodsImgForm.value.windowPicList.splice(evt.newIndex, 0, goodsImgForm.value.windowPicList.splice(evt.oldIndex, 1)[0])
        var newArray = goodsImgForm.value.windowPicList.slice(0)
        goodsImgForm.value.windowPicList = []
        nextTick(() => {
          goodsImgForm.value.windowPicList = newArray
        })
      },
    })
  }

  // 显示编辑属性的弹框
  const showModal = (type: string, info?: any) => {
    editAttrType.value = type
    editAttrInfo.value = info
    showEditAttrModal.value = true
  }

  // 选择标签
  const selTag = (item: any) => {
    let index = selTagList.value.findIndex((e: any) => e.name == item.dataFromRestApi.name)
    if (index == -1) {
      let obj = {
        id: item.dataFromRestApi.id,
        name: item.dataFromRestApi.name,
        slug: item.dataFromRestApi.slug,
      }
      selTagList.value.push(obj)
    }
  }

  // 快速添加标签
  const quickAddTag = async () => {
    if (!tagName.value) return Message.error('请填写标签名称')
    if (tagList.value.length <= 0) {
      // let arr = tagName.value.trim().split(',')
      let arr = [tagName.value.trim()]
      let params: any = {
        param: {
          create: [],
        },
        shopId: productInfo.value.shopId,
      }
      arr.forEach((e) => {
        let obj = {
          name: e,
          description: '',
          slug: e,
        }
        params.param.create.push(obj)
      })

      const res: any = await batchTag(params)
      if (res) {
        tagName.value = ''
        getTag()
        selTagList.value = [...selTagList.value, ...params.param.create]
        Message.success('添加标签成功')
      }
    } else {
      let item = tagList.value.find((e: any) => e.id == tagName.value)
      selTag(item)
    }
  }

  const getDetail = async () => {
    let id = router.query.id || ''
    const res: any = await saleGetById({ id })
    if (res) {
      productInfo.value = res.data || {}
      // 回显标题
      form.value.title = productInfo.value.dataFromRestApi.name || ''
      // form.value.desc = productInfo.value.dataFromRestApi.description.replace(/[\\]/g, '').replace(/\n/g, '') || ''
      form.value.desc = productInfo.value.dataFromRestApi.description.replace(/[\\]/g, '').replace(/\n/g, '') || ''

      form.value.desc = form.value.desc.slice(0, form.value.desc.length - 1)

      form.value.shortDesc = productInfo.value.dataFromRestApi.short_description || ''
      // 商品主题sku
      subjectSku.value = productInfo.value.dataFromRestApi.sku
      // 标签
      selTagList.value = productInfo.value.dataFromRestApi.tags || []
      // 属性反显
      attrList.value = productInfo.value.dataFromRestApi.attributes || []
      // 类目
      if (productInfo.value.dataFromRestApi.categories) {
        let arr = productInfo.value.dataFromRestApi.categories || []
        selCateGoryIds.value = arr.map((e: any) => e.id)
        expandedCateGoryIds.value = arr.map((e: any) => e.id)
      }
      // 商品发布状态
      goodsPublishForm.value = {
        visiable: productInfo.value.dataFromRestApi.status,
        range: productInfo.value.dataFromRestApi.catalog_visibility,
        featured: productInfo.value.dataFromRestApi.featured,
        operationUserId: productInfo.value.operationUserId,
      }
      // 图片
      goodsImgForm.value.windowPicList = productInfo.value.dataFromRestApi.images || []
      // 将商品链接拆解放
      let url = productInfo.value.dataFromRestApi.permalink || ''
      if (url) {
        const regex = /product\//
        const parts = url.split(regex)
        domain.value = 'https://www.jewelryodm.com/' + 'product/'
        form.value.link = parts[1]
      }
    }
  }

  const setNewTreeData = (data: any) => {
    data.forEach((item: any) => {
      item.title = item.dataFromRestApi.name
      item.key = item.dataFromRestApi.id
      if (!item.children[0]) item.children = null
      if (item.children) {
        setNewTreeData(item.children)
      }
    })
  }

  const getBrand = async () => {
    let params = {
      pageSize: 9999999,
    }
    const res: any = await getBrandList(params)
    brandList.value = res.data.records || []
  }
  const getTag = async () => {
    let params = {
      shopIdList: [productInfo.value.shopId],
      pageSize: 9999999,
    }
    const res: any = await tagRollPage(params)
    // tagList.value = res.data.list || []
  }
  const getCategory = async () => {
    let params = {
      shopId: productInfo.value.shopId,
    }
    const res: any = await listAllCategoryTreeByShopId(params)
    categoryList.value = res.data || []
    setNewTreeData(categoryList.value)
  }

  const saveAttr = (info: any) => {
    if (editAttrType.value == 'add') {
      info.forEach((e: any) => {
        let index = attrList.value.findIndex((item: any) => item.id == e.id)
        if (index != -1) {
          attrList.value.splice(index, 1, e)
        } else if (index == -1) {
          attrList.value.push(e)
        }
      })
    } else {
      let index = attrList.value.findIndex((item: any) => item.id == info.id)
      if (index != -1) {
        attrList.value.splice(index, 1, info)
      }
    }
  }

  // 价格保存
  const getPrice = () => {
    let arr = productInfo.value.dataFromRestApi.meta_data || []
    let flag = arr.findIndex((item: any) => item.key == 'wpcpq_enable' && item.value == 'override')
    let item: any = {}
    if (flag > -1) {
      item = arr.find((e: any) => e.key == 'wpcpq_prices') || {}
    }
    let obj = JSON.parse(item.value || '{}')
    let newArrList = obj.tiers.sort((a: any, b: any) => a.quantity - b.quantity)
    let firstObj = newArrList[0] || {}

    return { ...firstObj, price: Number(firstObj.price.replace(/[^\d.]/g, '')) || null }
  }

  // 价格保存
  const getBigPrice = (list?: any) => {
    let arr = productInfo.value.dataFromRestApi.meta_data || []
    let flag = arr.findIndex((item: any) => item.key == 'wpcpq_enable' && item.value == 'override')
    let item: any = {}
    if (flag > -1) {
      item = arr.find((e: any) => e.key == 'wpcpq_prices') || {}
    }
    let obj = JSON.parse(item.value || '{}')
    let newArrList = obj.tiers.sort((a: any, b: any) => b.quantity - a.quantity)
    let firstObj = newArrList[0] || {}

    return { ...firstObj, price: Number(firstObj.price.replace(/[^\d.]/g, '')) || null }
  }

  // 编辑基本数据
  const saveBasicInfoOrgoodsData = async () => {
    if (curTab.value == '1') {
      let params: any = {
        param: {
          update: [],
        },
        shopId: productInfo.value.shopId,
      }
      let obj = {
        id: productInfo.value.dataFromRestApi.id,
        goodsType: form.value.goodsType,
        permalink: `${domain.value}${form.value.link}`,
        name: form.value.title.trim(),
        description: form.value.desc,
        short_description: form.value.shortDesc,
        tags: selTagList.value,
        price: getBigPrice().price,
        regular_price: getBigPrice().price,
        sale_price: getBigPrice().price,
      }

      params.param.update.push(obj)
      const res: any = await batchProduct(params)
      if (res) {
        Message.success('保存成功')
      }
    } else {
      // 商品属性
      let basicInfoParams: any = {
        param: {
          update: [
            {
              id: productInfo.value.dataFromRestApi.id,
              attributes: attrList.value,
            },
          ],
        },
        shopId: productInfo.value.shopId,
      }

      // 商品变体设置售价规则（spu层次）
      let ruleItem = setSpuPriceRule()
      if (!ruleItem) return
      // 如果已经存在规则则修改
      let basicGoodsInfo = { ...ruleItem, ...basicInfoParams.param.update[0], price: getBigPrice().price, regular_price: getBigPrice().price, sale_price: getBigPrice().price }
      let obj = { key: 'min_quantity', value: getPrice().quantity }
      if (basicGoodsInfo.meta_data) {
        let index = basicGoodsInfo.meta_data.findIndex((item: any) => item.key == 'min_quantity')
        if (index == -1) {
          basicGoodsInfo.meta_data.push(obj)
        } else {
          basicGoodsInfo.meta_data[index].value = getPrice().quantity
        }
      } else {
        basicGoodsInfo.meta_data = [obj]
      }

      basicInfoParams.param.update[0] = basicGoodsInfo
      // 商品变体数据
      let goodsVaritantParams: any = {
        param: {
          create: [],
          delete: [...ProductVariant.value.delIds],
          update: [],
        },
        productId: productInfo.value.dataFromRestApi.id,
        shopId: productInfo.value.shopId,
      }
      let arr = ProductVariant.value.autoCreateTableList

      // 商品销售规则设置到sku上面

      // 设置时间
      let priceRule = ProductVariant.value.salePriceForm || {}
      if (priceRule.salePlanTime[0]) {
        let start = priceRule.salePlanTime[0]
        let end = priceRule.salePlanTime[1]
        arr.map((e: any) => {
          e.date_on_sale_from = dayjs(start).format('YYYY-MM-DDTHH:MM:ss')
          e.date_on_sale_from_gmt = dayjs(start).format('YYYY-MM-DDTHH:MM:ss')
          e.date_on_sale_to = dayjs(end).format('YYYY-MM-DDTHH:MM:ss')
          e.date_on_sale_to_gmt = dayjs(end).format('YYYY-MM-DDTHH:MM:ss')
        })
      }

      // 商品变体设置售价规则（sku层次）
      // let flag: any = setVariantPriceRule(arr)
      // if (!flag) return
      arr.forEach((e: any) => {
        e.price = getBigPrice().price
        e.sale_price = getBigPrice().price
        e.regular_price = getBigPrice().price
        let index = e.meta_data.findIndex((e) => e.key == 'min_quantity')
        if (index == -1) {
          e.meta_data.push({
            key: 'min_quantity',
            value: getPrice().quantity,
          })
        } else {
          e.meta_data[index].value = getPrice().quantity
        }

        if (e.id) {
          goodsVaritantParams.param.update.push(e)
        } else {
          goodsVaritantParams.param.create.push(e)
        }
      })
      const res: any = await batchProduct(basicInfoParams)
      if (res) {
        Message.success('商品属性信息保存成功')
      }
      const res1: any = await batchProductVariation(goodsVaritantParams)
      if (res1) {
        Message.success('商品变体信息保存成功')
      }
    }
  }

  const setSpuPriceRule = () => {
    let priceRule = ProductVariant.value.salePriceForm || {}
    let ruleItem: any = {
      meta_data: productInfo.value?.dataFromRestApi?.meta_data || [],
    }
    //一口价 disable 阶梯价
    if (priceRule.priceType == 'disable') {
      if (priceRule.num <= 0) {
        Message.error('请输入起订量')
        return false
      }

      // 一口价规则
      let index = ruleItem.meta_data.findIndex((item: any) => item.key == 'wpcpq_enable')
      if (index == -1) {
        ruleItem.meta_data.push({ key: 'wpcpq_enable', value: 'disable' })
      } else {
        ruleItem.meta_data[index].value = 'disable'
      }
      let index1 = ruleItem.meta_data.findIndex((item: any) => item.key == 'min_quantity')
      if (index1 == -1) {
        ruleItem.meta_data.push({ key: 'min_quantity', value: priceRule.num })
      } else {
        ruleItem.meta_data[index1].value = priceRule.num
      }
    } else {
      // 阶梯价规则
      let arr: any = []
      priceRule.priceList.forEach((el: any) => {
        let obj = { quantity: el.startNum, price: el.price, text: '', endNum: el.endNum }
        arr.push(obj)
      })
      let index = ruleItem.meta_data.findIndex((item: any) => item.key == 'wpcpq_enable')
      if (index == -1) {
        ruleItem.meta_data.push({ key: 'wpcpq_enable', value: 'override' })
      } else {
        ruleItem.meta_data[index].value = 'override'
      }
      let index1 = ruleItem.meta_data.findIndex((item: any) => item.key == 'wpcpq_prices')
      let itemInfo = {
        apply: 'all',
        apply_val: '',
        layout: 'default',
        method: 'volume',
        role: 'all',
        tiers: arr,
      }

      if (index1 == -1) {
        ruleItem.meta_data.push({ key: 'wpcpq_prices', value: JSON.stringify(itemInfo) })
      } else {
        ruleItem.meta_data[index1].value = JSON.stringify(itemInfo)
      }
    }

    return ruleItem

    // variantList.forEach((e: any) => {
    // 如果有促销时间
    //   if (obj.salePlanTime[0]) {
    //     let start = obj.salePlanTime[0]
    //     let end = obj.salePlanTime[1]
    //     e.date_on_sale_from = dayjs(start).format('YYYY-MM-DDTHH:MM:ss')
    //     e.date_on_sale_from_gmt = dayjs(start).format('YYYY-MM-DDTHH:MM:ss')
    //     e.date_on_sale_to = dayjs(end).format('YYYY-MM-DDTHH:MM:ss')
    //     e.date_on_sale_to_gmt = dayjs(end).format('YYYY-MM-DDTHH:MM:ss')
    //   }

    //   // 看是否已经存在规则,存在修改，不存在新增
    //   let index = e.meta_data.findIndex((item: any) => item.key == 'wpcpq_enable')
    //   if (index == -1) {
    //     e.meta_data.push({ key: 'wpcpq_enable', value: 'disable' })
    //     let metaDataItem = { key: 'min_quantity', value: obj.num }
    //     e.meta_data.push(metaDataItem)
    //   } else {
    //     e.meta_data[index].value = 'disable'
    //     let valuIndex = e.meta_data.findIndex((item: any) => item.key == 'min_quantity')
    //     if (valuIndex == -1) {
    //       let metaDataItem = { key: 'min_quantity', value: obj.num }
    //       e.meta_data.push(metaDataItem)
    //     } else {
    //       e.meta_data[valuIndex].value = obj.num
    //     }
    //   }
    //   // })
    // } else {
    //   // variantList.forEach((e: any) => {
    //   let arr: any = []
    //   obj.priceList.forEach((el: any) => {
    //     let obj = { quantity: el.startNum, price: el.price, text: '', endNum: el.endNum }
    //     arr.push(obj)
    //   })
    //   // 看是否已经存在规则,存在修改，不存在新增
    //   let index = e.meta_data.findIndex((item: any) => item.key == 'wpcpq_enable')
    //   if (index == -1) {
    //     e.meta_data.push({ key: 'wpcpq_enable', value: 'override' })
    //     let metaDataItem: any = { key: 'wpcpq_prices', value: JSON.stringify({ tiers: arr }) }
    //     e.meta_data.push(metaDataItem)
    //   } else {
    //     e.meta_data[index].value = 'override'
    //     let valuIndex = e.meta_data.findIndex((item: any) => item.key == 'wpcpq_prices')
    //     if (valuIndex == -1) {
    //       let metaDataItem: any = { key: 'wpcpq_prices', value: JSON.stringify({ tiers: arr }) }
    //       e.meta_data.push(metaDataItem)
    //     } else {
    //       e.meta_data[valuIndex].value = JSON.stringify({ tiers: arr })
    //     }
    //   }
    //   // })
    // }
    // return true
  }

  // 商品发布状态
  const savePublishStatus = async () => {
    let params: any = {
      param: {
        update: [
          {
            id: productInfo.value.dataFromRestApi.id,
            catalog_visibility: goodsPublishForm.value.range,
            status: goodsPublishForm.value.visiable,
            featured: goodsPublishForm.value.featured,
            price: getBigPrice().price,
            regular_price: getBigPrice().price,
            sale_price: getBigPrice().price,
          },
        ],
      },
      shopId: productInfo.value.shopId,
      operationUserId: '',
    }
    if (goodsPublishForm.value.operationUserId) bindOperaTion()
    const res: any = await batchProduct(params)
    if (res) {
      Message.success('保存成功')
    }
  }

  // 绑定运营
  const bindOperaTion = async () => {
    let params = {
      createOrUpdateDocList: [
        {
          id: productInfo.value.id,
          operationUserId: goodsPublishForm.value.operationUserId,
          operationUserName: '',
        },
      ],
    }
    if (goodsPublishForm.value.operationUserId) {
      let item = userList.value.find((e: any) => e.id == goodsPublishForm.value.operationUserId)
      if (item) params.createOrUpdateDocList[0].operationUserName = item.userName
    }

    await saleBatchUpdate(params)
  }

  // 商品图片
  const saveProductImg = async () => {
    let params: any = {
      param: {
        update: [
          {
            id: productInfo.value.dataFromRestApi.id,
            images: goodsImgForm.value.windowPicList,
            price: getBigPrice().price,
            regular_price: getBigPrice().price,
            sale_price: getBigPrice().price,
          },
        ],
      },
      shopId: productInfo.value.shopId,
    }
    const res: any = await batchProduct(params)
    if (res) {
      Message.success('保存成功')
    }
  }
  // 商品分类
  const saveProductCategory = async () => {
    let arr: any = []
    selCateGoryIds.value.forEach((e: any) => {
      let item = findChildrenArray(categoryList.value, e, 'key')
      let obj = {
        name: item.dataFromRestApi.name,
        slug: item.dataFromRestApi.slug,
        id: item.dataFromRestApi.id,
      }
      arr.push(obj)
    })
    let params: any = {
      param: {
        update: [
          {
            id: productInfo.value.dataFromRestApi.id,
            categories: arr,
            price: getBigPrice().price,
            regular_price: getBigPrice().price,
            sale_price: getBigPrice().price,
          },
        ],
      },
      shopId: productInfo.value.shopId,
    }
    const res: any = await batchProduct(params)
    if (res) {
      Message.success('保存成功')
    }
  }

  const saveProperty = (data: any) => {
    attrList.value = data
  }

  const getUSerList = async () => {
    let params = {
      depart: false,
      pageNum: 1,
      pageSize: 100000,
    }
    const res: any = await getOrganizesUser(params)
    userList.value = res?.data?.records || []
  }

  const jump = () => {
    window.open(productInfo.value.mallSourceUrl)
  }

  const handleSearchTag = async (value: string) => {
    if (value) {
      try {
        loading.value = true
        let params = {
          shopIdList: [productInfo.value.shopId],
          pageSize: 9999999,
          keyword: value,
          keywordType: 'dataFromRestApi.name',
          searchType: 'exact',
        }
        const res: any = await tagRollPage(params)
        tagList.value = res.data.list || []
        if (tagList.value.length <= 0) tagName.value = value
      } catch (error) {}
      loading.value = false
    } else {
      spuList.value = []
    }
  }

  const handleSelectTag = (id: string) => {
    let item = tagList.value.find((e: any) => e.id == id)
    selTag(item)
  }

  const deleteSelTag = (i: number) => {
    // tagName.value = ''
    // tagList.value = []
    selTagList.value.splice(i, 1)
  }

  onMounted(async () => {
    getUSerList()
    rowDropProductImg()
    await getDetail() //获取商品详情
    await getBrand() //获取商品品牌
    await getTag() //获取商品标签
    await getCategory() //获取商品类目
  })
</script>

<style lang="less" scoped>
  .publish-detail-con {
    display: flex;
    .left {
      width: 75%;
      .tab-top {
        background-color: white;
      }
      .goods-desc {
        .title {
          .more-language {
            display: flex;
            margin-left: 20px;
            div {
              padding: 5px;
              background-color: #dddddd;
              margin-left: 10px;
              border-top-left-radius: 3px;
              border-top-right-radius: 3px;
              font-size: 12px;
              color: #7f7f7f;
            }
            .active {
              color: #333333;
              background-color: white;
            }
          }
          .title-input {
            width: 100%;
            padding: 5px 10px;
            background-color: white;
          }
        }
        .desc,
        .short-desc {
          width: 100%;
          padding: 5px 10px;
          background-color: white;
        }

        .goods-tag {
          width: 100%;
          background-color: white;
          padding: 5px 10px;
        }
      }
      .goods-data {
        .goods-type {
          width: 100%;
          background-color: white;
          padding: 10px 20px;
          margin: 10px 0;
        }
        .goods-main-body {
          width: 100%;
          background-color: white;
          padding: 10px 20px;
          .spu-info-con {
            min-height: 80px;
            width: 100%;
            border: 1px solid #d7d7d7;
            padding: 5px;
            box-sizing: border-box;
            border-radius: 5px;

            .sku-detail-con {
              position: relative;
              .del-btn {
                position: absolute;
                right: 10px;
                top: 10px;
              }
            }
          }
        }
        .goods-property,
        .goods-variant {
          width: 100%;
          background-color: white;
          padding: 10px 20px;
        }
      }
    }
    .right {
      flex: 1;
      margin-left: 10px;
      margin-right: 15px;
      .goods-status,
      .edit-info-box {
        .top {
          display: flex;
          justify-content: space-between;
          align-items: center;
          background: #d7d7d7;
          padding: 5px 15px 5px 10px;
          box-sizing: border-box;
        }
        .bottom {
          background-color: white;
          padding: 10px 0;
          box-sizing: border-box;
        }
      }

      .goods-img {
        .master-img-con {
          text-align: center;
          padding: 10px;
          box-sizing: border-box;
          // border: 1px solid #d7d7d7;
          :deep(.arco-upload-picture-card) {
            width: 200px;
            height: 200px;
          }
          :deep(.arco-upload-list-picture) {
            width: 200px;
            height: 200px;
          }
        }
        .product-img-box {
          overflow: hidden;
          .box {
            margin-top: 5px;
            // min-height: 180px;
            // border-right: 1px solid #d7d7d7;
            .box-img-con {
              float: left;
              width: 80px;
              height: 80px;
              position: relative;
              margin: 0 10px 10px 0;

              .mask {
                height: 20px;
                width: 80px;
                position: absolute;
                bottom: 0;
                left: 0;
                // display: none;
                z-index: 1;
                background: rgba(0, 0, 0, 0.5);
                .btn-con {
                  width: 80px;
                  color: white;
                  font-size: 14px;
                  text-align: center;
                  // margin-top: 5px;
                  align-items: center;
                }
              }
            }
          }
        }
      }
    }
  }
</style>
